package com.tool_stdy.Reflect;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import com.tool_stdy.Model.User;

public class ReflectTest {

	/**
	 * 通过反射获取类中的成员变量
	 * @param clazz
	 * @param newInstance
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	public static void FieldTest(Class<?> clazz,Object newInstance) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException{
		String fieldName="name";
		Field declaredField = clazz.getDeclaredField(fieldName);//获取私有的
		declaredField.setAccessible(true);//取消权限验证private的
		declaredField.set(newInstance, "nihao");
		System.out.println(declaredField.get(newInstance));
	}
	
	public static void MethodTest(Class<?> clazz,Object newInstance) throws Exception{
		String methodName="show";
		Method method = clazz.getMethod(methodName, String.class,int.class);
		Object invoke = method.invoke(newInstance, "nihao",33);//方法执行
		System.out.println(invoke);
	}
	
	
	public static void main(String[] args) {
		try {
            Class<User> clazz = (Class<User>) Class.forName("com.tool_stdy.Model.User");
			User newInstance = clazz.newInstance();//获取实例对象
			/**
			 * 带参数的构造方法
			 */
//			Constructor<User> constructor = clazz.getConstructor(String.class,int.class);
//			User newInstance = constructor.newInstance("你好",3);
			//FieldTest(clazz,newInstance); 
			MethodTest(clazz,newInstance);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
